/*
 * @Description: 上传图片界面
 * @Version: V1.0.0
 * @Author: 黄鑫
 * @Date: 2024-08-21 14:31:37
 * @LastEditors: 黄鑫
 * @LastEditTime: 2025-05-12
 * @FilePath: UploadImageView.dart
 * @Props: 
 * @Remarks: 
 */
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:hx_base/pages/BaseToast.dart';
import 'package:hx_base/resource/Assets.dart';
import 'package:hx_base/utils/PermissionCheckUtils.dart';
import 'package:image_picker/image_picker.dart';

class UploadImageView extends StatelessWidget {
  // 选择相机理由
  String cameraReason;

  // 选择相册理由
  String photoReason;

  ///组件边距
  EdgeInsets? margin;
  EdgeInsets? padding;
  // 图片宽
  double width;
  // 图片高
  double height;

  // 最大图片数量
  int maxlength;

  // 纵向间距
  double? runSpacing;

  // 横向间距
  double? spacing;

  // 返回图片数组
  Function(List<File> imageList) callbackImage;

  UploadImageView({
    super.key,
    required this.cameraReason,
    required this.photoReason,
    required this.width,
    required this.height,
    required this.callbackImage,
    required this.maxlength,
    this.spacing,
    this.runSpacing,
    this.margin,
    this.padding,
  });

  var list = [File("")].obs;

  // 定义支持的图片后缀
  List<String> supportedImageExtensions = [
    '.jpg',
    '.jpeg',
    '.png',
    '.gif',
    '.bmp',
    '.webp',
  ];

  addImage() async {
    showCupertinoModalPopup(
      context: Get.context!,
      builder: (builder) {
        return CupertinoActionSheet(
          actions: [
            CupertinoActionSheetAction(
              onPressed: () {
                clickCamera();
                Get.back();
              },
              child: Text("拍照"),
            ),
            CupertinoActionSheetAction(
              onPressed: () {
                clickPhoto();
                Get.back();
              },
              child: Text("相册"),
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            child: Text("取消"),
            onPressed: () {
              Get.back();
            },
          ),
        );
      },
    );
  }

  // 相册
  clickPhoto() async {
    ImagePicker imagePicker = ImagePicker();
    final XFile? image =
        await imagePicker.pickImage(source: ImageSource.gallery);

    if (image != null) {
      // 判断是否为支持的图片类型
      bool isImage = supportedImageExtensions
          .any((extension) => image.path.endsWith(extension));
      if (isImage) {
        list.add(File(image.path));
        if (list.length >= maxlength + 1) {
          list.removeAt(0);
        }
        callbackImage(list.where((e) => e.path.isNotEmpty).toList());
      } else {
        BaseToast.showError("请选择正确的图片类型");
      }
    }
  }

  // 相机
  clickCamera() async {
    if (await PermissionCheckUtils.camera(cameraReason)) {
      ImagePicker imagePicker = ImagePicker();
      XFile? image = await imagePicker.pickImage(
          source: ImageSource.camera, imageQuality: 50);
      if (image != null) {
        list.add(File(image.path));
        if (list.length >= maxlength + 1) {
          list.removeAt(0);
        }
        callbackImage(list.where((e) => e.path.isNotEmpty).toList());
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: margin,
      padding: padding,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: EdgeInsets.only(bottom: 12.h),
            child: Text(
              "添加图片",
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.bold,
                color: Color(0xFF333333),
              ),
            ),
          ),
          Obx(() => Wrap(
                runSpacing: runSpacing ?? 10,
                spacing: spacing ?? 10,
                children: list.map((e) {
                  return Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(6.r),
                      border: Border.all(
                        width: 0.5,
                        color: Color(0xFFB7B7B7),
                      ),
                    ),
                    clipBehavior: Clip.hardEdge,
                    width: width,
                    height: height,
                    child: Stack(
                      children: [
                        e.path.isNotEmpty
                            ? Image.file(
                                e,
                                fit: BoxFit.cover,
                                width: double.infinity,
                                height: double.infinity,
                              )
                            : GestureDetector(
                                onTap: () => addImage(),
                                child: Container(
                                  color: Colors.transparent,
                                  width: double.infinity,
                                  height: double.infinity,
                                  alignment: Alignment.center,
                                  child: Image.asset(
                                    Assets.imagesCameraIcon,
                                    width: 20.w,
                                    height: 20.w,
                                    package: "hx_base",
                                  ),
                                ),
                              ),
                        Visibility(
                          visible: e.path.isNotEmpty,
                          child: Positioned(
                            right: 0,
                            top: 0,
                            child: IconButton(
                              alignment: Alignment.topRight,
                              style: ButtonStyle(
                                padding:
                                    WidgetStatePropertyAll(EdgeInsets.all(3)),
                                minimumSize: WidgetStatePropertyAll(Size(0, 0)),
                                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                                backgroundColor:
                                    WidgetStatePropertyAll(Color(0x65000000)),
                                shape: WidgetStatePropertyAll(
                                  RoundedRectangleBorder(
                                    borderRadius: BorderRadius.only(
                                      bottomLeft: Radius.circular(6.r),
                                    ),
                                  ),
                                ),
                              ),
                              onPressed: () {
                                list.remove(e);
                                if (list.isEmpty) {
                                  list.insert(0, File(""));
                                } else if (list.length < maxlength &&
                                    list.first.path.isNotEmpty) {
                                  list.insert(0, File(""));
                                }
                                callbackImage(list
                                    .where((e) => e.path.isNotEmpty)
                                    .toList());
                              },
                              icon: Icon(
                                Icons.close,
                                color: Colors.white,
                                size: 16,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                }).toList(),
              ))
        ],
      ),
    );
  }
}
